<template>
  <div class="app-container">
    <!-- 搜索区域 -->
    <el-form :inline="true" :model="queryParams" class="search-form">
      <el-form-item label="规格名称">
        <el-input
            v-model="queryParams.specName"
            placeholder="请输入规格名称"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 操作按钮 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="Plus" @click="handleAdd">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="Edit" :disabled="!single" @click="handleUpdate">修改</el-button>

      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="Delete" :disabled="multiple.length === 0" @click="handleDelete(null)">删除
        </el-button>
      </el-col>
    </el-row>

    <!-- 表格 -->
    <el-table
        v-loading="loading"
        :data="specList"
        @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55"/>
      <el-table-column prop="categoryName" label="分类名称" width="150"/>
      <el-table-column prop="specName" label="规格名称" min-width="180"/>
      <el-table-column label="规格值" min-width="300">
        <template #default="{ row }">
          <div v-for="(values, name) in parseSpecValue(row.specValue)" :key="name" class="spec-value-item">
            <strong>{{ name }}：</strong>
            <el-tag
                v-for="(val, idx) in values"
                :key="idx"
                size="small"
                type="info"
                style="margin-right: 5px; margin-bottom: 5px;"
            >
              {{ val }}
            </el-tag>
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="createTime" label="创建时间" width="160"/>
      <el-table-column label="操作" width="120" fixed="right">
        <template #default="{ row }">
          <el-button link type="primary" @click="handleUpdate(row)">修改</el-button>
          <el-button link type="danger" @click="handleDelete(row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <pagination
        v-show="total > 0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
    />

    <!-- 弹窗 -->
    <el-dialog
        :title="dialogTitle"
        v-model="dialogVisible"
        width="800px"
        @close="closeDialog"
    >
      <el-form ref="formRef" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="分类" prop="categoryId">
          <el-cascader
              v-model="form.categoryId"
              :options="categoryOptions"
              :props="{ value: 'value', label: 'label', checkStrictly: true }"
              placeholder="请选择分类"
              clearable
              filterable
              @change="handleCategoryChange"
          />
        </el-form-item>

        <el-form-item label="规格名称" prop="specName">
          <el-input v-model="form.specName" placeholder="请输入规格名称"/>
        </el-form-item>

        <el-divider content-position="left">规格值设置</el-divider>

        <div v-for="(spec, index) in form.specValues" :key="index" class="spec-item">
          <el-row :gutter="10">
            <el-col :span="4">
              <el-input
                  v-model="spec.name"
                  placeholder="规格名（如：颜色）"
              />
            </el-col>
            <el-col :span="16">
              <el-tag
                  v-for="(value, vIndex) in spec.values"
                  :key="vIndex"
                  closable
                  @close="removeValue(index, vIndex)"
                  style="margin-right: 5px; margin-bottom: 5px;"
              >
                {{ value }}
              </el-tag>
              <el-input
                  v-if="inputVisible[index]"
                  ref="inputRefs"
                  v-model="inputValue"
                  class="input-new-tag"
                  size="small"
                  @keyup.enter="handleInputConfirm(index)"
                  @blur="handleInputConfirm(index)"
              />
              <el-button
                  v-else
                  class="button-new-tag"
                  @click="showInput(index)"
              >
                + 添加值
              </el-button>
            </el-col>
            <el-col :span="4" class="text-right">
              <el-button type="danger" icon="Delete" size="small" @click="removeSpec(index)">删除</el-button>
            </el-col>
          </el-row>
        </div>

        <el-button type="primary" plain @click="addSpecItem">+ 添加新规格</el-button>

        <div class="dialog-footer" style="margin-top: 20px;">
          <el-button @click="closeDialog">取消</el-button>
          <el-button type="primary" @click="submitForm">确定</el-button>
        </div>
      </el-form>
    </el-dialog>
  </div>
</template>

<script setup>
import {ref, nextTick, onMounted} from 'vue'
import {ElMessage, ElMessageBox} from 'element-plus'
import {
  listProductSpec,
  getCategoryCascader,
  getProductSpec,
  updateProductSpec,
  addProductSpec,
  delProductSpec
} from '@/api/product/productSpec.js'

// ========== 列表相关 ==========
const loading = ref(true)
const total = ref(0)
const specList = ref([])
const queryParams = ref({
  pageNum: 1,
  pageSize: 10,
  categoryId: null,
  specName: ''
})
const single = ref(null)
const multiple = ref([])

// ========== 分类选项 ==========
const categoryOptions = ref([])

// ========== 弹窗相关 ==========
const dialogVisible = ref(false)
const dialogTitle = ref('')
const formRef = ref(null)
const form = ref({
  id: null,
  categoryId: null,
  specName: '',
  specValues: [] // [{ name: '颜色', values: ['白','红'] }]

})
// 监听级联变化
const handleCategoryChange = (value) => {
  // value 是数组，如 [1, 5, 12] 或 [3]
  form.value.categoryId = value && value.length > 0 ? value[value.length - 1] : null
}
const inputVisible = ref([])
const inputValue = ref('')
const inputRefs = ref([])

// ========== 表单规则 ==========
const rules = {
  categoryId: [{required: true, message: '请选择分类', trigger: 'change'}],
  specName: [{required: true, message: '请输入规格名称', trigger: 'blur'}],
}

// ========== 方法 ==========
const getList = async () => {
  loading.value = true
  try {
    const res = await listProductSpec(queryParams.value)
    specList.value = res.rows || []
    total.value = res.total || 0
  } catch (error) {
    console.error('获取规格列表失败:', error)
  } finally {
    loading.value = false
  }
}

const handleQuery = () => {
  queryParams.value.pageNum = 1
  getList()
}

const resetQuery = () => {
  queryParams.value = {
    pageNum: 1,
    pageSize: 10,
    categoryId: null,
    specName: ''
  }
  getList()
}

const handleSelectionChange = (selection) => {
  single.value = selection.length === 1 ? selection[0] : null
  multiple.value = selection
}

const handleAdd = () => {
  dialogTitle.value = '新增商品规格'
  resetForm()
  dialogVisible.value = true
}

const handleUpdate = async (row) => {
  const record = row || single.value
  if (!record) {
    ElMessage.warning('请先选择一条数据')
    return
  }

  dialogTitle.value = '修改商品规格'
  dialogVisible.value = true

  try {
    const res = await getProductSpec(record.id)
    if (res.code === 200) {
      loadFormData(res.data)
    } else {
      ElMessage.error(res.msg || '获取详情失败')
      dialogVisible.value = false
    }
  } catch (error) {
    console.error('加载规格详情失败:', error)
    ElMessage.error('网络错误，请重试')
    dialogVisible.value = false
  }
}

const handleDelete = async (row) => {
  const records = row ? [row] : multiple.value

  if (records.length === 0) {
    ElMessage.warning('请先选择要删除的数据')
    return
  }

  if (records[0] instanceof Event || records[0]?.constructor?.name === 'PointerEvent') {
    ElMessage.error('删除失败：收到了事件对象，请检查 @click 传参')
    console.error('错误的 records:', records)
    return
  }

  const ids = records.map(r => r.id).filter(id => id != null)

  if (ids.length === 0) {
    ElMessage.error('未获取到有效 ID')
    return
  }

  ElMessageBox.confirm(`是否确认删除选中的 ${ids.length} 条规格？`, '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      const res = await delProductSpec(ids)
      if (res.code === 200) {
        ElMessage.success('删除成功')
        getList()
      } else {
        ElMessage.error(res.msg || '删除失败')
      }
    } catch (error) {
      console.error('删除失败:', error)
      ElMessage.error('删除失败，请重试')
    }
  })
}

// ========== 弹窗方法 ==========
const resetForm = () => {
  formRef.value?.resetFields()
  form.value = {
    id: null,
    categoryId: null,
    categoryPath: [],
    specName: '',
    specValues: []
  }
  inputVisible.value = []
}

const loadFormData = (record) => {
  resetForm()
  form.value.id = record.id
  form.value.categoryId = record.categoryId
  form.value.specName = record.specName

  if (record.specValue) {
    try {
      const parsed = JSON.parse(record.specValue)
      form.value.specValues = Object.entries(parsed).map(([name, values]) => ({
        name,
        values: Array.isArray(values) ? values : [values]
      }))
    } catch (e) {
      console.warn('解析 specValue 失败')
    }
  }
}

const closeDialog = () => {
  dialogVisible.value = false
  resetForm()
}

const addSpecItem = () => {
  form.value.specValues.push({name: '', values: []})
  inputVisible.value.push(false)
}

const showInput = (index) => {
  inputVisible.value[index] = true
  nextTick(() => {
    const inputs = inputRefs.value
    if (inputs[index]) {
      inputs[index].focus()
    }
  })
}

const handleInputConfirm = (index) => {
  if (inputValue.value.trim()) {
    form.value.specValues[index].values.push(inputValue.value.trim())
  }
  inputVisible.value[index] = false
  inputValue.value = ''
}

const removeValue = (specIndex, valueIndex) => {
  form.value.specValues[specIndex].values.splice(valueIndex, 1)
}

const removeSpec = (index) => {
  form.value.specValues.splice(index, 1)
  inputVisible.value.splice(index, 1)
}

const submitForm = async () => {
  if (!formRef.value) return

  try {
    await formRef.value.validate()
  } catch (error) {
    console.warn('表单验证失败:', error)
    return
  }

  // 构造 specValue：将 specValues 数组转为对象，再 stringify
  const specValueObj = {}
  for (const item of form.value.specValues) {
    if (item.name && item.values && item.values.length > 0) {
      specValueObj[item.name] = item.values
    }
  }

  const submitData = {
    id: form.value.id,
    categoryId: form.value.categoryId,
    specName: form.value.specName,
    specValue: JSON.stringify(specValueObj) // 后端期望的是字符串
  }

  try {
    let res
    if (form.value.id) {
      // 修改
      console.log(submitData)
      res = await updateProductSpec(submitData)
    } else {
      // 新增
      res = await addProductSpec(submitData)
    }

    if (res.code === 200) {
      ElMessage.success(res.msg || '操作成功')
      dialogVisible.value = false
      getList() // 刷新列表
    } else {
      ElMessage.error(res.msg || '操作失败')
    }
  } catch (error) {
    console.error('提交失败:', error)
    ElMessage.error('网络错误，请稍后重试')
  }
}

// ========== 工具方法 ==========
const parseSpecValue = (valueStr) => {
  if (!valueStr) return {}
  try {
    return JSON.parse(valueStr)
  } catch (e) {
    return {}
  }
}

// ========== 初始化 ==========
onMounted(async () => {
  // 获取分类级联数据
  try {
    const res = await getCategoryCascader()
    console.log('分类级联数据:', res.data)
    categoryOptions.value = Array.isArray(res.data) ? res.data : []
  } catch (error) {
    console.error('获取分类失败:', error)
  }
  // 获取规格列表
  getList()
})
</script>

<style scoped>
.search-form {
  margin-bottom: 10px;
}

.mb8 {
  margin-bottom: 8px;
}

.spec-value-item {
  margin-bottom: 5px;
}

.spec-item {
  margin-bottom: 10px;
}

.text-right {
  display: flex;
  align-items: center;
  justify-content: flex-end;
}

.input-new-tag {
  width: 90px;
  margin-left: 10px;
  vertical-align: bottom;
}

.button-new-tag {
  margin-left: 10px;
  height: 32px;
  line-height: 30px;
  padding-top: 0;
  padding-bottom: 0;
}

.dialog-footer {
  text-align: right;
}
</style>